package com.dcy.singleton.type5;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2021/1/19 14:44
 */
public class SingletonTest05 {
    public static void main(String[] args) {
        // 测试
        System.out.println("懒汉式(线程安全，同步代码块)");
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);
        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());
    }
}


/**
 * 懒汉式(线程安全，同步代码块)
 */
class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

    // 通过一个静态的公有方法，当使用到该方法时，才去创建instance
    // 即懒汉式
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class){
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}